<?php

namespace App\Supports\Payment\Methods\Adawxmini;

use Exception;
use Illuminate\Support\Facades\Log;
use App\Supports\Payment\Methods\Method;
use App\Supports\Payment\Contracts\MethodPay;

class PayOrder extends Method implements MethodPay
{
	public function validate($order = null)
	{
		if ($order->isGoldBeanOrder() or $order->isGoldStormOrder()) {
			fail('金店相关订单仅支持金店账户付款');
		}
		if ($order->isPaid()) {
			fail('目标订单已支付');
		}
		if ($order->isClosed()) {
			fail('目标订单已关闭');
		}
		if ($order->isCancelled()) {
			fail('目标订单已取消');
		}
	}

	public function info($order = null)
	{
		$orderNo = 'order_'.$order->number;
		$title = '支付有点东西订单: ' . $order->number;
		$payAmt = $order->total_amount;
        $notifyUrl = route('web.payments.adapay.notify');

		return [
			'adapay_func_code' => 'wxpay.createOrder',
			'app_id' => ($this->channel->config())['app_id'],
			'order_no' => $orderNo,
			'pay_amt' => $payAmt,
			'goods_title' => $title,
			'goods_desc' => $title,
			'notify_url' => $notifyUrl,
		];
	}

	public function pay($order = null)
	{
		$this->validate($order);

		try {

			$info = $this->info($order);

			$pay = $this->channel->pay($info);

			if ($pay->isError()) {
				fail($pay->result['error_msg']);
			} else {
				$result = $pay->result['expend'];
				return [
					'g_id' => $result['g_id'],
					'path' => $result['path'],
					'pre_order_id' => $result['pre_order_id'],
					'scheme_code' => $result['scheme_code'],
					'wx_h5_pay_url' => $result['wx_h5_pay_url'],
				];
			}
		} catch (Exception $exception) {
			return fail('支付暂不可用!');
		}
	}
}
